package se.haaga.jsupervision.monitor.linux;

import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class LinuxMonitors {
	
	private static LinuxMonitors instance = null;
	
	private Map<String, LinuxMonitor> linuxMonitors = null;
	
	private LinuxMonitors() {
		linuxMonitors = new LinkedHashMap<String, LinuxMonitor>();
		setLocalhostConnection(); // Only for testing
	}
	
	private void setLocalhostConnection() {
		String username = System.getProperty("user.name");
		String host = "localhost";
		LinuxMonitor con = new LinuxMonitor(host, username, 22);
		addMonitor(username + "@" + host, con);
	}

	public static LinuxMonitors getInstance() {
		if (instance == null) {
			instance = new LinuxMonitors();
		}
		return instance;
	}
	
	@Override
	protected Object clone() throws CloneNotSupportedException {
		throw new CloneNotSupportedException();
	}
	
	public void addMonitor(String name, LinuxMonitor monitor) {
		linuxMonitors.put(name, monitor);
	}
	
	public LinuxMonitor getLinuxMonitor(String name) {
		return linuxMonitors.get(name);
	}
	
	public List<String> getLinuxMonitorsNames() {
		return new LinkedList<String>(linuxMonitors.keySet());
	}
	
	public void closeAllConnections() {
		Set<String> keys = linuxMonitors.keySet();
		for (String key : keys) {
			LinuxMonitor linuxMonitor = linuxMonitors.get(key);
			linuxMonitor.closeConnection();
		}
		List<String> names = getLinuxMonitorsNames();
		for (String name : names) {
			linuxMonitors.remove(name);
		}
	}

}
